package com.geeyuu.android.activity;

import java.lang.ref.WeakReference;
import java.util.ArrayList;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.geeyuu.android.GeeApplication;
import com.geeyuu.android.GeeApplication.GetLocationListener;
import com.geeyuu.android.GeePrefrence;
import com.geeyuu.android.R;
import com.geeyuu.android.customview.InertiaListView;
import com.geeyuu.android.customview.InertiaListView.OnFootViewClickListener;
import com.geeyuu.android.customview.InertiaListView.OnRefreshListener;
import com.geeyuu.android.model.BaseUserInfo;
import com.geeyuu.android.service.DataKey;
import com.geeyuu.android.service.ProtocolCommand;
import com.geeyuu.android.utils.AndroidUtil;
import com.geeyuu.android.utils.CommonUtil;
import com.geeyuu.android.utils.ImageLoder;

public class Activity0 extends BaseActivity {
    
    private InertiaListView mInertiaListView;
    private DataAdapter mDataAdapter;
    private ArrayList<BaseUserInfo> mArrayListUser;
    private Handler mHandler;
    private int screenWidth;
    private int shouldHeight;
    
    private Button topRightButton;
    private PopupWindow popupWindow;
    
    /**
     * 动画方式选择
     */
    public static boolean isFromActivity0 = true;
    
    private String orderBy = DataKey.S_VALUE_ORDER_BY_DISTANCE;
    private String role = DataKey.S_VALUE_ROLE_ALL;
    private boolean isFilterOnline = true;
    
    private ImageLoder imageLoder = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.TAG = "Activity0";
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity0_layout);
        
        imageLoder = new ImageLoder(this);
        mHandler = new MyHandler(this);
        
        DisplayMetrics metrics = new DisplayMetrics(); 
        getWindowManager().getDefaultDisplay().getMetrics(metrics); 
        screenWidth = metrics.widthPixels;
        shouldHeight = screenWidth / 4;
        
        initTitleViews();
        initContentViews();
        
        startBindService();
        
    }
    
    @Override
    protected void onPause() {
        super.onPause();
        
        if (popupWindow.isShowing()) {
            popupWindow.dismiss();
        }
    }
    
    private OnClickListener mOnClickListener = new OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
            case R.id.top_right_button:
                if(popupWindow.isShowing()){
                    popupWindow.dismiss();
                }else{
                    popupWindow.showAsDropDown(topRightButton, 0, 0);
                }
                break;
            case R.id.order_by_distance_text_view:
                orderBy = DataKey.S_VALUE_ORDER_BY_DISTANCE;
                distanceTextView.setCompoundDrawablesWithIntrinsicBounds(R.drawable.order_by_distance, 0, R.drawable.selected_icon, 0);
                popularityTextView.setCompoundDrawablesWithIntrinsicBounds(R.drawable.order_by_popularity, 0, 0, 0);
                break;
            case R.id.order_by_popularity_text_view:
                orderBy = DataKey.S_VALUE_ORDER_BY_POPULARITY;
                distanceTextView.setCompoundDrawablesWithIntrinsicBounds(R.drawable.order_by_distance, 0, 0, 0);
                popularityTextView.setCompoundDrawablesWithIntrinsicBounds(R.drawable.order_by_popularity, 0, R.drawable.selected_icon, 0);
                break;
            case R.id.role_all_text_view:
                role = DataKey.S_VALUE_ROLE_ALL;
                roleAllTextView.setCompoundDrawablesWithIntrinsicBounds(R.drawable.role_all_icon, 0, R.drawable.selected_icon, 0);
                role_1_TextView.setCompoundDrawablesWithIntrinsicBounds(R.drawable.role_1_icon, 0, 0, 0);
                role_0_TextView.setCompoundDrawablesWithIntrinsicBounds(R.drawable.role_0_icon, 0, 0, 0);
                break;
            case R.id.role_1_text_view:
                role = DataKey.S_VALUE_ROLE_1;
                roleAllTextView.setCompoundDrawablesWithIntrinsicBounds(R.drawable.role_all_icon, 0, 0, 0);
                role_1_TextView.setCompoundDrawablesWithIntrinsicBounds(R.drawable.role_1_icon, 0, R.drawable.selected_icon, 0);
                role_0_TextView.setCompoundDrawablesWithIntrinsicBounds(R.drawable.role_0_icon, 0, 0, 0);
                break;
            case R.id.role_0_text_view:
                role = DataKey.S_VALUE_ROLE_0;
                roleAllTextView.setCompoundDrawablesWithIntrinsicBounds(R.drawable.role_all_icon, 0, 0, 0);
                role_1_TextView.setCompoundDrawablesWithIntrinsicBounds(R.drawable.role_1_icon, 0, 0, 0);
                role_0_TextView.setCompoundDrawablesWithIntrinsicBounds(R.drawable.role_0_icon, 0, R.drawable.selected_icon, 0);
                break;
            case R.id.comfire_button:
                popupWindow.dismiss();
                if(mInertiaListView.isComplete()){
                    mInertiaListView.setSelection(0);
                    mInertiaListView.autoRefresh();
                }
                break;
            case R.id.just_online_text_view:
                isFilterOnline = !isFilterOnline;
                TextView justOnlineTextView = (TextView)v;
                if(isFilterOnline){
                    justOnlineTextView.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.checkbox_selected, 0);
                }else{
                    justOnlineTextView.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.checkbox, 0);
                }
                break;
            }
        }
    };

    private void initTitleViews() {
        
        Button topLeftButton = (Button)findViewById(R.id.top_left_button);
        topLeftButton.setVisibility(View.VISIBLE);
        topLeftButton.setText("找人");
        topLeftButton.setCompoundDrawablesWithIntrinsicBounds(R.drawable.title_icon_tab0, 0, 0, 0);
        topLeftButton.setPadding(AndroidUtil.dip2px(this, 10), 0, 0, 0);
        ViewGroup.LayoutParams vl = topLeftButton.getLayoutParams();
        if(null == vl){
            vl = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.FILL_PARENT);
        }else{
            vl.width = ViewGroup.LayoutParams.WRAP_CONTENT;
            vl.height = ViewGroup.LayoutParams.FILL_PARENT;
        }
        topLeftButton.setLayoutParams(vl);
        
        topRightButton = (Button)findViewById(R.id.top_right_button);
        topRightButton.setVisibility(View.VISIBLE);
        topRightButton.setPadding(0, 0, AndroidUtil.dip2px(this, 27), 0);
        topRightButton.setCompoundDrawablesWithIntrinsicBounds(R.drawable.vertical_line, 0, R.drawable.more_filter_button, 0);
        topRightButton.setOnClickListener(mOnClickListener);
        
    }
    
    private TextView distanceTextView;
    private TextView popularityTextView;
    
    private TextView roleAllTextView;
    private TextView role_1_TextView;
    private TextView role_0_TextView;
    
    private void initContentViews() {
        
        mArrayListUser = BaseUserInfo.getAroundUser(this, PAGE_SIZE, BaseUserInfo.ORDER_BY_DISTANCE, BaseUserInfo.FILTER_ROLE_NOT_SET, BaseUserInfo.USER_ONLINE);
        
        View filterContainer = getLayoutInflater().inflate(R.layout.find_friend_popup_layout, null);
        distanceTextView = (TextView)filterContainer.findViewById(R.id.order_by_distance_text_view);
        popularityTextView = (TextView)filterContainer.findViewById(R.id.order_by_popularity_text_view);
        distanceTextView.setOnClickListener(mOnClickListener);
        popularityTextView.setOnClickListener(mOnClickListener);
        roleAllTextView = (TextView)filterContainer.findViewById(R.id.role_all_text_view);
        role_1_TextView = (TextView)filterContainer.findViewById(R.id.role_1_text_view);
        role_0_TextView = (TextView)filterContainer.findViewById(R.id.role_0_text_view);
        roleAllTextView.setOnClickListener(mOnClickListener);
        role_1_TextView.setOnClickListener(mOnClickListener);
        role_0_TextView.setOnClickListener(mOnClickListener);
        filterContainer.findViewById(R.id.comfire_button).setOnClickListener(mOnClickListener);
        filterContainer.findViewById(R.id.just_online_text_view).setOnClickListener(mOnClickListener);
        popupWindow = new PopupWindow(filterContainer, WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT);
        
        mInertiaListView = (InertiaListView)findViewById(R.id.grid_list_view);
        mInertiaListView.setRefreshTime(GeePrefrence.getRefreshTimeStr(getApplicationContext()));
        mInertiaListView.setDividerHeight(0);
        mDataAdapter = new DataAdapter(this, R.layout.list_view_item);
        mInertiaListView.setAdapter(mDataAdapter);
        final GeeApplication geeApplication = (GeeApplication)getApplication();
        mInertiaListView.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onStartRefresh() { //刷新
                geeApplication.setLocationListener(new GetLocationListener() {
                    @Override
                    public void onFinish(double[] lonAndLat) {
                        mHandler.obtainMessage(CODE_REQUEST_REFRESH_AROUND_USER, lonAndLat).sendToTarget();
                    }
                    @Override
                    public void onFail(double[] lastLonAndLat) {
                        mHandler.sendEmptyMessage(CODE_SHOW_TOAST);
                    }
                });
            }
        });
        mInertiaListView.setFootViewListenter(new OnFootViewClickListener() {
            @Override
            public void onClick(View v) { //更多
                geeApplication.setLocationListener(new GetLocationListener() {
                    @Override
                    public void onFinish(double[] lonAndLat) {
                        mHandler.obtainMessage(CODE_REQUEST_GET_MORE_AROUND_USER, lonAndLat).sendToTarget();
                    }
                    @Override
                    public void onFail(double[] lastLonAndLat) {
                        mHandler.sendEmptyMessage(CODE_SHOW_TOAST);
                    }
                });
            }
        });
        
    }
    
    @Override
    protected void onConnectServiceCallBack() {
//        if(mArrayListUser.size() < PAGE_SIZE){
            mInertiaListView.autoRefresh();
//        }
    }

    @Override
    protected void onReceiveMsgFromService(int cmd, Bundle bundle, boolean isMsgNormal) {
        switch (cmd) {
        case ProtocolCommand.CMD_QUERY_AROUND_USERS_28_SIZE:
            if(isMsgNormal){
                mHandler.sendEmptyMessage(CODE_REFRESH_DATA);
            }else{
                mHandler.sendEmptyMessage(CODE_LOAD_DATA_FAIL);
            }
            break;
        }
    }
    
    private static final int PAGE_SIZE = 28;
    private int currentPage = 0;
    private static final int CODE_REFRESH_DATA = 0;
    private static final int CODE_LOAD_DATA_FAIL = 1;
    private static final int CODE_REQUEST_REFRESH_AROUND_USER = 2;
    private static final int CODE_REQUEST_GET_MORE_AROUND_USER = 3;
    private static final int CODE_SHOW_TOAST = 4;
    private static final int CODE_COMPLETE_REFRESH_DATA = 5;

    static class MyHandler extends Handler{
        
        private final WeakReference<Activity0> activity0;
        
        
        public MyHandler(Activity activity){
            activity0 = new WeakReference<Activity0>((Activity0)activity);
        }
        
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
            case CODE_REFRESH_DATA:
                
                //加载刷新数据，然后刷新list
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        int _orderby = BaseUserInfo.ORDER_BY_NOT_SET;
                        int _role = BaseUserInfo.FILTER_ROLE_NOT_SET;
                        int _justOnline = BaseUserInfo.FILTER_JUST_ONLINE_NOT_SET;
                        
                        if(activity0.get().orderBy == DataKey.S_VALUE_ORDER_BY_DISTANCE){
                            _orderby = BaseUserInfo.ORDER_BY_DISTANCE;
                        }else if(activity0.get().orderBy == DataKey.S_VALUE_ORDER_BY_POPULARITY){
                            _orderby = BaseUserInfo.ORDER_BY_POP_VALUE;
                        }
                        
                        if(activity0.get().role == DataKey.S_VALUE_ROLE_0){
                            _role = BaseUserInfo.ROLE_0;
                        }else if(activity0.get().role == DataKey.S_VALUE_ROLE_1){
                            _role = BaseUserInfo.ROLE_1;
                        }else if(activity0.get().role == DataKey.S_VALUE_ROLE_05){
                            _role = BaseUserInfo.ROLE_05;
                        }
                        
                        if(activity0.get().isFilterOnline){
                            _justOnline = BaseUserInfo.USER_ONLINE;
                        }
                        
                        activity0.get().mArrayListUser = BaseUserInfo.getAroundUser(activity0.get(), PAGE_SIZE * (activity0.get().currentPage+1), _orderby, _role, _justOnline);
                        
                        sendEmptyMessage(CODE_COMPLETE_REFRESH_DATA);
                    }
                }).start();
                
                break;
                
            case CODE_LOAD_DATA_FAIL:
                String timeStr = CommonUtil.getCurrentTimeStr();
                GeePrefrence.setRefreshTimeStr(activity0.get(), timeStr);
                activity0.get().mInertiaListView.setRefreshComplete(timeStr);
                AndroidUtil.showToast(activity0.get().getApplicationContext(), "加载数据失败，请重试");
                break;
                
            case CODE_REQUEST_REFRESH_AROUND_USER:
                double[] loc = (double[])msg.obj;
                Bundle bundle = new Bundle();
                if(null == loc){
                    String[] locStr = GeePrefrence.getMyLocation(activity0.get()).split(",");
                    bundle.putString(DataKey.S_KEY_LON_AND_LAT, locStr[0]+","+locStr[1]);
                }else{
                    bundle.putString(DataKey.S_KEY_LON_AND_LAT, loc[0]+","+loc[1]);
                }
                bundle.putString(DataKey.S_KEY_ORDER_BY, activity0.get().orderBy);
                bundle.putString(DataKey.S_KEY_ROLE_FILTER, activity0.get().role);
                bundle.putString(DataKey.S_KEY_ONLINE_FILTER, activity0.get().isFilterOnline ? DataKey.S_VALUE_JUST_ON_LINE : DataKey.S_VALUE_NOT_JUST_ON_LINE);
                bundle.putString(DataKey.S_KEY_PAGE_INDEX, "0");
                activity0.get().sendMsgToService(ProtocolCommand.CMD_QUERY_AROUND_USERS_28_SIZE, bundle);
                activity0.get().currentPage = 0;
                break;
                
            case CODE_REQUEST_GET_MORE_AROUND_USER:
                double[] loc2 = (double[])msg.obj;
                Bundle bundle2 = new Bundle();
                bundle2.putString(DataKey.S_KEY_LON_AND_LAT, loc2[0]+","+loc2[1]);
                bundle2.putString(DataKey.S_KEY_ORDER_BY, activity0.get().orderBy);
                bundle2.putString(DataKey.S_KEY_ROLE_FILTER, activity0.get().role);
                bundle2.putString(DataKey.S_KEY_ONLINE_FILTER, activity0.get().isFilterOnline ? DataKey.S_VALUE_JUST_ON_LINE : DataKey.S_VALUE_NOT_JUST_ON_LINE);
                activity0.get().currentPage++;
                bundle2.putString(DataKey.S_KEY_PAGE_INDEX, String.valueOf(activity0.get().currentPage));
                activity0.get().sendMsgToService(ProtocolCommand.CMD_QUERY_AROUND_USERS_28_SIZE, bundle2);
                break;
                
            case CODE_SHOW_TOAST:
                AndroidUtil.showToast(activity0.get().getApplicationContext(), "读取数据失败，请稍后重试");
                String timeStr3 = CommonUtil.getCurrentTimeStr();
                activity0.get().mInertiaListView.setRefreshComplete(timeStr3);
                break;
                
            case CODE_COMPLETE_REFRESH_DATA:
                String timeStr2 = CommonUtil.getCurrentTimeStr();
                GeePrefrence.setRefreshTimeStr(activity0.get(), timeStr2);
                activity0.get().mInertiaListView.setRefreshComplete(timeStr2);
                activity0.get().mDataAdapter.notifyDataSetChanged();
                break;
            }
        }
        
    }
    
    class DataAdapter extends BaseAdapter{

        private final WeakReference<Activity0> activity0;
        private int count;
        private int resLayoutId;
        private int itemHeight;
        private final int[] textViewResId = {R.id.text_distance0, R.id.text_distance1, R.id.text_distance2, R.id.text_distance3};
        private final int[] avatarViewResId = {R.id.avatar0, R.id.avatar1, R.id.avatar2, R.id.avatar3};
        private final int[] viewsContainerResId = {R.id.avatar0_container,R.id.avatar1_container,R.id.avatar2_container,R.id.avatar3_container};
        private final int[] isOnlineIconResId = {R.id.is_online_icon0, R.id.is_online_icon1, R.id.is_online_icon2, R.id.is_online_icon3};
        
        public DataAdapter(Activity activity, int layoutId){
            activity0 = new WeakReference<Activity0>((Activity0)activity);
            resLayoutId = layoutId;
            int dataSize = activity0.get().mArrayListUser.size();
            count = dataSize < 4 ? 0 : dataSize/4;
            itemHeight = activity0.get().shouldHeight;
        }
        @Override
        public int getCount() {
            return count;
        }
        @Override
        public Object getItem(int arg0) {
            return null;
        }
        @Override
        public long getItemId(int position) {
            return 0;
        }
        @Override
        public void notifyDataSetChanged() {
            int dataSize = activity0.get().mArrayListUser.size();
            count = dataSize < 4 ? 0 : dataSize/4;
            super.notifyDataSetChanged();
        }
        
        private OnClickListener containerListener = new OnClickListener() {
            @Override
            public void onClick(View v) {
                Activity0.isFromActivity0 = true;
                long userId = (Long)v.getTag();
                Intent intent = new Intent(activity0.get(), FriendProfileAvtivity.class);
                intent.putExtra("userId", userId);
                activity0.get().startActivity(intent);
            }
        };
        
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = convertView;
            if(null == view){
                view = activity0.get().getLayoutInflater().inflate(resLayoutId, parent, false);
            }
            int size = activity0.get().mArrayListUser.size();
            size = size < 4 ? size : 4;
            for (int i=0; i<size; i++) {
                
                BaseUserInfo user = activity0.get().mArrayListUser.get(position * 4 + i);
                
                TextView textViewDistance = (TextView) view.findViewById(textViewResId[i]);
                textViewDistance.setText(user.distance + "km");
                
                ImageView onlineIconView = (ImageView)view.findViewById(isOnlineIconResId[i]);
                if(user.isOnline == BaseUserInfo.USER_ONLINE){
                    onlineIconView.setImageResource(R.drawable.online_icon);
                }else{
                    onlineIconView.setImageResource(R.drawable.offline_icon);
                }
                
                ImageView avatarView = (ImageView)view.findViewById(avatarViewResId[i]);
                imageLoder.add(user.mainPhotoID, avatarView, true);
                
                View container = view.findViewById(viewsContainerResId[i]);
                container.setTag(user.uid);
                container.setOnClickListener(containerListener);
                
            }
            ViewGroup.LayoutParams vl = view.getLayoutParams();
            if(null == vl){
                vl = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, itemHeight);
            }else{
                vl.width = ViewGroup.LayoutParams.FILL_PARENT;
                vl.height = itemHeight;
            }
            view.setLayoutParams(vl);
            return view;
        }
        
    }
    
    @Override
    protected void onDestroy() {
        stopBindService();
        if(null != imageLoder){
            imageLoder.destory();
        }
        super.onDestroy();
    }

}
